﻿using UnityEngine;
using System.Collections;

public class ShipPlayerController : MonoBehaviour
{
	public float m_speed = 1f;
	public float m_rotationSpeed = 1f;

    public float m_impulseMultiplier;
	
	public float m_friction;
	public float m_stopThreashold = 0.01f;

	public Vector3 m_velocity;
	public Vector3 m_targetVelocity;
	public float m_turnFriction = 1f;

    public Collider2D m_moveArea;


	void Start()
	{
	}
	
	void Update()
	{
		if (Input.GetKey(KeyCode.LeftArrow))
		{
			gameObject.transform.Rotate(new Vector3(0f, 0f, m_rotationSpeed * Time.deltaTime));
		}

		if (Input.GetKey(KeyCode.RightArrow))
		{
			gameObject.transform.Rotate(new Vector3(0f, 0f, -m_rotationSpeed * Time.deltaTime));
		}

		Vector3 dir = gameObject.transform.rotation * Vector3.right;
		gameObject.transform.position += dir * m_speed * Time.deltaTime;

		if (m_targetVelocity.magnitude > 0f)
		{
			m_targetVelocity = m_targetVelocity * m_friction;
			if (m_targetVelocity.magnitude < m_stopThreashold)
			{
				m_targetVelocity = new Vector3();
			}
		}

		m_velocity = Vector3.Lerp(m_velocity, m_targetVelocity, Time.deltaTime * m_turnFriction);// (m_velocity + newVelocity) * 0.5f;
		if (m_velocity.magnitude < m_stopThreashold)
		{
			m_velocity = new Vector3();
		}
		else
		{
			// move/rotate object
			gameObject.transform.position += m_velocity * Time.deltaTime;
			float angle = Mathf.Atan2(m_velocity.normalized.y, m_velocity.normalized.x) * Mathf.Rad2Deg;
			transform.rotation = Quaternion.Euler(0f, 0f, angle);
		}

		if (Input.GetMouseButton(1))
		{
			Vector3 mouse = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0f));
			mouse.z = gameObject.transform.position.z;
			Vector2 direction = gameObject.transform.position - mouse;
			direction.Normalize();
			m_targetVelocity = direction * m_speed;
		}

        if (!m_moveArea.bounds.Contains(transform.position))
        {
            Vector3 new_pos = transform.position;
            if (transform.position.x > m_moveArea.bounds.max.x)
            {
                new_pos.x = m_moveArea.bounds.min.x;
            }
            else if (transform.position.x < m_moveArea.bounds.min.x)
            {
                new_pos.x = m_moveArea.bounds.max.x;
            }

            if (transform.position.y > m_moveArea.bounds.max.y)
            {
                new_pos.y = m_moveArea.bounds.min.y;
            }
            else if (transform.position.y < m_moveArea.bounds.min.y)
            {
                new_pos.y = m_moveArea.bounds.max.y;
            }

            transform.position = new_pos;
        }
	}
}